package org.xx.armory.spring5.jdbc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.xx.armory.spring5.domain.Book;

import java.util.Date;
import java.util.List;

import static org.apache.commons.lang3.StringUtils.trimToEmpty;

@Component
public class BookProvider {
    @Autowired
    private BookDao bookDao;

    @Transactional
    public Book save(
            Book book
    ) {
        if (book.getId() == 0) {
            // Insert
            final var c = this.bookDao.insert(
                    book.getTitle(),
                    book.getAuthor(),
                    book.getPubDate(),
                    book.getPrice(),
                    book.getAmount()
            );
            return c > 0 ? this.bookDao.findById(this.bookDao.getLastRowLongId()) : null;
        } else {
            // Update
            final var c = this.bookDao.update(
                    book.getId(),
                    book.getTitle(),
                    book.getAuthor(),
                    book.getPubDate(),
                    book.getPrice(),
                    book.getAmount()
            );
            if (c > 0) {
                return this.bookDao.findById(book.getId());
            } else {
                return null;
            }
        }
    }

    @Transactional(readOnly = true)
    public List<Book> findAll(
            String key,
            Date startDate,
            Date endDate,
            Pageable pageable
    ) {
        return this.bookDao.setPageable(pageable).findAll(trimToEmpty(key), startDate, endDate);
    }

    @Transactional(readOnly = true)
    public int count(
            String key,
            Date startDate,
            Date endDate
    ) {
        return this.bookDao.count(trimToEmpty(key), startDate, endDate);
    }
}
